﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace HyperPin_Database_Editor
{
    public partial class CheckTablesDialog : Form
    {
        public TableDatabase tableDatabase;

        public CheckTablesDialog()
        {
            InitializeComponent();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        enum MediaType {BackglassImage, TableImage, TableVideo, WheelImage};
        string[] MediaDirectory = {"Backglass Images", "Table Images", "Table Videos", "Wheel Images"};

        string getMediaDirectory(MediaType mediaType)
        {
            string hyperPinDirectory = MainForm.theMainForm.hyperPinDirectory;
            if (hyperPinDirectory == null)
            {
                return null;
            }

            return Path.Combine(hyperPinDirectory, "Media", "Visual Pinball", MediaDirectory[(int)mediaType]);
        }

        string getTableDirectory()
        {
            // check the settings section and find the table path.
            string currentSettingsFileName = MainForm.theMainForm.currentSettingsFileName;
            if (currentSettingsFileName == null)
            {
                return null;
            }

            IniFile settingsINI = new IniFile(currentSettingsFileName);
            if (settingsINI == null)
            {
                return null;
            }

            string tableDirectory = settingsINI.IniReadValue("Visual Pinball", "Table_Path");
            if (tableDirectory == null)
            {
                return null;
            }

            return tableDirectory;
        }

        string[] GetTableFiles()
        {
            HashSet<string> tableFiles = new HashSet<string>();

            string tableDirectory = getTableDirectory();
            foreach (string fileName in Directory.EnumerateFiles(tableDirectory, "*.vpt"))
            {
                Console.WriteLine(fileName);

                string tableName = Path.GetFileNameWithoutExtension(fileName);
                tableFiles.Add(tableName);
            }

            return tableFiles.ToArray();
        }

        bool MediaFileExists(string tableName, MediaType mediaType)
        {
            string searchFileName = String.Format("{0}.*", tableName);
            foreach (string fileName in Directory.EnumerateFiles(getMediaDirectory(mediaType), searchFileName))
            {
                //Console.WriteLine(fileName);
                return true;
            }

            return false;
        }

        void WriteLine(string line) 
        {
            textBoxDetails.Text += line + "\r\n";
            textBoxDetails.Refresh();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            HashSet<string> allTables = new HashSet<string>();
            string[] tableFiles = GetTableFiles();
            allTables.UnionWith(tableFiles);

            string[] databaseNames = tableDatabase.GetTableNames();
            allTables.UnionWith(databaseNames);

            // progress bar goes from 0 to the number of tables
            progressBarCheckTables.Maximum = allTables.Count;
            progressBarCheckTables.Value = 0;

            string tableDirectory = getTableDirectory();

            WriteLine(String.Format("# Checking; {0} tables.", allTables.Count));
            WriteLine(String.Format("#   {0} in table directory.", tableFiles.Length));
            WriteLine(String.Format("#   {0} in HyperPin database.", databaseNames.Length));

            foreach (string tableName in allTables)
            {
                bool hasError = false;

                if (!tableFiles.Contains(tableName))
                {
                    WriteLine(String.Format("-TF: {0} : Missing table file.", tableName));
                    hasError = true;
                }

                if (databaseNames.Contains(tableName))
                {
                    TableSummary table = tableDatabase.GetTableSummary(tableName);
                    if (!MediaFileExists(table.TableDescription, MediaType.BackglassImage))
                    {
                        WriteLine(String.Format("-BG: {0} : Missing backglass image.", tableName));
                        hasError = true;
                    }

                    if (!MediaFileExists(table.TableDescription, MediaType.TableImage))
                    {
                        WriteLine(String.Format("-TI: {0} : Missing table image.", tableName));
                        hasError = true;
                    }

                    if (!MediaFileExists(table.TableDescription, MediaType.TableVideo))
                    {
                        WriteLine(String.Format("-TV: {0} : Missing table video.", tableName));
                        hasError = true;
                    }

                    if (!MediaFileExists(table.TableDescription, MediaType.WheelImage))
                    {
                        WriteLine(String.Format("-WI: {0} : Missing wheel image.", tableName));
                        hasError = true;
                    }
                } 
                else
                {
                    WriteLine(String.Format("-DB: {0} : Missing database entry.", tableName));
                    hasError = true;
                }

                if (!hasError)
                {
                    //WriteLine(String.Format("+OK: {0}", tableName));
                }

                // update progress bar
                progressBarCheckTables.Value += 1;

            }

            WriteLine("# done.");
#if false
            foreach (TableSummary tableSummary in tableDatabase)
            {
                textBoxDetails.Text += String.Format("\r\nChecking {0}...", tableSummary.TableName);
                textBoxDetails.Refresh();
                string tableFileName = Path.Combine(tableDirectory, tableSummary.TableName + ".vpt");
                textBoxDetails.Text += String.Format("\r\n\tTable file [{0}]: {1}", tableFileName,
                    File.Exists(tableFileName) ? "Ok" : "Missing");

                textBoxDetails.Text += "\r\n";
                // update progress bar
                progressBarCheckTables.Value += 1;
            }
#endif
        }
    }
}
